import React, { useEffect, useRef, useState } from 'react';
import './videoBackground.scss';

interface VideoBackgroundProps {
  activeData?: boolean;
}

const VideoBackground: React.FC<VideoBackgroundProps> = ({ activeData = true }) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    // 预加载视频
    const handleCanPlayThrough = () => {
      setIsLoaded(true);
    };

    video.addEventListener('canplaythrough', handleCanPlayThrough);
    video.load(); // 开始预加载

    return () => {
      video.removeEventListener('canplaythrough', handleCanPlayThrough);
    };
  }, []);

  useEffect(() => {
    if (!activeData || !isLoaded) return;

    const video = videoRef.current;
    if (!video) return;

    // 开始播放动画序列
    const startAnimation = () => {
      // 1秒渐入
      setIsVisible(true);
      video.play();

      // 5秒后开始渐出（总时长5秒：1秒渐入 + 2秒持续 + 2秒渐出）
      setTimeout(() => {
        setIsVisible(false);
      }, 2000); // 2秒后开始渐出（1秒渐入 + 1秒持续）
    };

    // 重置视频到开始位置
    video.currentTime = 0;
    startAnimation();

    // 监听视频结束事件，重置状态
    const handleVideoEnd = () => {
      setIsVisible(false);
      video.currentTime = 0;
    };

    video.addEventListener('ended', handleVideoEnd);

    return () => {
      video.removeEventListener('ended', handleVideoEnd);
    };
  }, [activeData, isLoaded]);

  if (!activeData) {
    return null;
  }

  return (
    <div className={`video-background ${isVisible ? 'fade-in' : 'fade-out'}`}>
      <video
        ref={videoRef}
        className="background-video"
        muted
        playsInline
        preload="auto"
      >
        <source src={require('@/assets/img/v.mp4')} type="video/mp4" />
        您的浏览器不支持视频播放。
      </video>
    </div>
  );
};

export default VideoBackground;